<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repos\BillboardRepo;
use App\Models\Billboard;
use App\Services\AMap; 
use App\Http\Requests\BillboardRequest;

class BillboardController extends Controller
{
    
    public function index(Request $request)
    {
        $where = [];
        if($request->keyword) {
            $where['code'] = $request->keyword;
        }
        $list = BillboardRepo::pages($where);

        return view('admin.billboard.index',compact('list'));
    }

    
    public function create()
    {     
       return view('admin.billboard.add');
    }

   
    public function store(BillboardRequest $request)
    {
        

        $rs['status'] = false;
        $rs['msg']    = '操作失败';
        $data = $request->except(['_token']);
        $flag = BillboardRepo::find(['code'=>$request->code]);
        if($flag) {
            $rs['msg'] = '编号已存在';
            return response()->json($rs); 
        }

        $map = AMap::coordiateToAddress($data['lnglat']);
        $data['city']     = $map['city'];
        $data['province'] = $map['province'];
        $flag = BillboardRepo::save($data);
        if($flag) {
            $rs['status'] = true;
            $rs['msg']    = '操作成功';
            return response()->json($rs);
        }
        return response()->json($rs);
    }

    
    public function show($id)
    {
        //
    }

   
    public function edit($id)
    {
        $data = Billboard::find($id);      
        return view('admin.billboard.edit',compact('data'));
    }

   
    public function update(Request $request, $id)
    {
        $rs['status'] = 'danger';
        $rs['msg']    = '操作失败';
        $data = $request->except(['_token','_method']);
        $map = AMap::coordiateToAddress($data['lnglat']);
        $data['city']     = $map['city'];
        $data['province'] = $map['province'];
        $flag = BillboardRepo::update($id,$data);
        if($flag) {
            $rs['status'] = 'success';
            $rs['msg']    = '操作成功';
            return back()->with('rs',$rs);
        }
        return back()->with('rs',$rs);
    }

    
    public function destroy($id)
    {
        $rs['status'] = 'danger';
        $rs['msg']    = '操作失败';
        $flag = BillboardRepo::delete($id);
        if($flag) {
            $rs['status'] = 'success';
            $rs['msg']    = '操作成功';
            return back()->with('rs',$rs);
        }
        return back()->with('rs',$rs);
    }
}
